<template>
    <div ref="containerRef" class="detail">
        <div class="detail_header">
            <a-page-header title="加盟商管理" :subtitle="type === 'edit' ? '修改' : '新增'" @back="onBack">
                <template #extra>
                    <a-button type="primary" @click="onReleased">
                        <template #icon>
                            <icon-save v-if="type === 'edit'"/>
                            <icon-send v-else/>
                        </template>
                        <template #default>
                            {{ type === 'edit' ? '保存' : '新增' }}
                        </template>
                    </a-button>
                </template>
            </a-page-header>
        </div>
        <div class="detail_content" style="display: flex; flex-direction: column;">
            <a-form ref="formRef" :model="form" :rules="rules" size="large" auto-label-width>
                <a-card title="基礎信息">
                    <a-form-item label="公司名字" field="enterpriseName">
                        <a-input v-model.trim="form.enterpriseName" placeholder="请输入公司名字"/>
                    </a-form-item>
                    <a-form-item label="公司简称" field="abbreviation">
                        <a-input v-model.trim="form.abbreviation" placeholder="请输入公司简称"/>
                    </a-form-item>
                    <a-form-item label="公司地址" field="provinceId">
                        <a-cascader v-model.trim="form.provinceId"
                                    allow-clear
                                    :options="addressList" placeholder="請選擇地址"
                                    :virtual-list-props="{height:200}"/>
                    </a-form-item>
                    <a-form-item label="细地址" field="detailedAddress">
                        <a-textarea
                            v-model.trim="form.detailedAddress"
                            placeholder="请输入细地址"
                            show-word-limit
                            :max-length="200"
                            :auto-size="{ minRows: 3, maxRows: 5 }"
                        />
                    </a-form-item>
                    <a-form-item label="立案证书" field="license">
                        <a-space>
                            <a-upload :show-preview-button="true" :show-file-list="true" :multiple="false"
                                      list-type="picture"
                                      :custom-request="handleMUpload">
                                <template #upload-button>
                                    <a-button type="primary" shape="round">
                                        <template #icon>
                                            <icon-upload/>
                                        </template>
                                        <template #default>上传</template>
                                    </a-button>
                                    <a-avatar v-if="form.license">
                                        <img
                                            :src="form.license"
                                        />
                                    </a-avatar>
                                </template>
                            </a-upload>
                            <FileSelect v-model="form.license"/>
                        </a-space>
                    </a-form-item>
                    <a-form-item label="荣誉证书" field="environmentPicture">
                        <a-space>
                            <a-upload @success="onChange" :show-preview-button="true" :show-file-list="true"
                                      :multiple="true" list-type="picture"
                                      :file-list="fileList"
                                      :custom-request="handleUpload">
                                <template #upload-button>
                                    <a-button type="primary" shape="round">
                                        <template #icon>
                                            <icon-upload/>
                                        </template>
                                        <template #default>上传</template>
                                    </a-button>
                                </template>
                            </a-upload>
                        </a-space>
                    </a-form-item>
                    <a-form-item label="公司状态" field="status">
                        <a-switch
                            v-model="form.enterpriseStatus"
                            :checked-value="1"
                            :unchecked-value="2"
                            checked-text="启用"
                            unchecked-text="停用"
                            type="round"
                        />
                    </a-form-item>
                </a-card>
                <a-card title="聯繫方式">
                    <a-form-item label="聯繫人" field="personName">
                        <a-input v-model.trim="form.personName" placeholder="请输入聯繫人"/>
                    </a-form-item>
                    <a-form-item label="聯繫电话" field="mobile">
                        <a-input v-model.trim="form.mobile" placeholder="请输入聯繫电话"/>
                    </a-form-item>
                    <a-form-item label="聯繫邮箱" field="email">
                        <a-input v-model.trim="form.email" placeholder="请输入聯繫邮箱"/>
                    </a-form-item>
                    <a-form-item label="聯繫座机" field="telephone">
                        <a-input v-model.trim="form.telephone" placeholder="请输入聯繫座机"/>
                    </a-form-item>
                    <a-form-item label="推荐人" field="recommend">
                        <a-input v-model.trim="form.recommend" placeholder="请输入推荐人"/>
                    </a-form-item>
                </a-card>
                <a-card title="登陸賬號" v-if="type !== 'edit'">
                    <a-form-item label="登陆账号" field="loginName">
                        <a-input v-model.trim="form.loginName" placeholder="请输入登陆账号"/>
                    </a-form-item>
                    <a-form-item label="登陸密碼" field="password">
                        <a-input v-model.trim="form.password" placeholder="请输入登陸密碼"/>
                    </a-form-item>
                </a-card>
            </a-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import {type FileItem, type FormInstance, Message, type RequestOption} from '@arco-design/web-vue'
import {addEnterprise, getEnterprise, updateEnterprise} from '@/apis/mch/enterprise'
import {useForm} from '@/hooks'
import {ref} from "vue";
import {useTabsStore} from "@/stores";
import {uploadFile} from "@/apis";
import {address} from '@/hooks/app'
import {encryptByRsa} from "@/utils/encrypt";
const router = useRouter()
const { addressList, getAddressList } = address()
const tabsStore = useTabsStore()
const route = useRoute()
const {id, type} = route.query
const emit = defineEmits<{
    (e: 'save-success'): void
}>()
const current = ref<number>(1)
const dataId = ref('')
const isUpdate = computed(() => !!dataId.value)
const formRef = ref<FormInstance>()
let fileList = reactive<FileItem[]>([])

const rules: FormInstance['rules'] = {
    enterpriseName: [{required: true, message: '请输入印語题目名稱'}],
    abbreviation: [{required: true, message: '请输入公司简称'}],
    personName: [{required: true, message: '请輸入聯繫人'}],
    mobile: [{required: true, message: '请輸入聯繫電話'}],
    email: [{required: true, message: '请輸入聯繫郵箱'}],
    provinceId: [{required: true, message: '請選擇地址'}],
    loginName: [{required: true, message: '请設置登陸賬號'}]

}
const {form, resetForm} = useForm({})

// 重置
const reset = () => {
    formRef.value?.resetFields()
    current.value = 1
    resetForm()
}
// 新增
const onAdd = async () => {
    reset()
    dataId.value = ''
    getAddressList();
}
// 修改
const onUpdate = async (id: string) => {
    resetForm()
    dataId.value = id
    const res = await getEnterprise(id)
    Object.assign(form, res.data)
    fileList.push(...res.data.items)
    getAddressList();
}
const onChange = (file: FileItem) => {
    const aa = reactive<FileItem>({uid: "", url: "", name: ""});
    aa.uid = file.uid
    aa.url = file.response?.data.url
    aa.name = file.name
    fileList.push(aa);
};
const handleUpload = (options: RequestOption) => {
    const controller = new AbortController();
    (async function requestWrap() {
        const {onProgress, onError, onSuccess, fileItem, name = 'file'} = options
        onProgress(20)
        const formData = new FormData()
        formData.append(name as string, fileItem.file as Blob)
        try {
            const res = await uploadFile(formData)
            Message.success('上传成功')
            onSuccess(res)
        } catch (error) {
            onError(error)
        }
    })()
    return {
        abort() {
            controller.abort()
        }
    }
}

const handleMUpload = (options: RequestOption) => {
    const controller = new AbortController();
    (async function requestWrap() {
        const {onProgress, onError, onSuccess, fileItem, name = 'file'} = options
        onProgress(20)
        const formData = new FormData()
        formData.append(name as string, fileItem.file as Blob)
        try {
            const res = await uploadFile(formData)
            form.license = res.data.url
            Message.success('上传成功')
            onSuccess(res)
        } catch (error) {
            onError(error)
        }
    })()
    return {
        abort() {
            controller.abort()
        }
    }
}
const onBack = () => {
    router.go(-1);
    tabsStore.closeCurrent(route.path)
}
const onReleased = async () => {
    const isInvalid = await formRef.value?.validate()
    if (isInvalid) return false
    try {
        form.items = fileList;
        if (type === 'edit') {
            form.enterpriseId = id
            await updateEnterprise(form)
            Message.success('修改成功')
        } else {
            form.password = !form.password.includes('*') ? encryptByRsa(form.password) : null
            await addEnterprise(form)
            Message.success('新增成功')
        }
        onBack()
        return true
    } catch (error) {
        console.error(error)
        return false
    }
}
onMounted(() => {
    // 当id存在与type为edit时，执行修改操作
    if (id && type === 'edit') {
        onUpdate(id as string)
    } else {
        onAdd()
    }
})
</script>

<style lang="scss" scoped>
fieldset {
    padding: 15px 15px 0 15px;
    margin-bottom: 10px;
    border: 1px solid var(--color-neutral-3);
    border-radius: 3px;
    height: 440px;
}

fieldset legend {
    color: rgb(var(--gray-10));
    padding: 2px 5px 2px 5px;
    border: 1px solid var(--color-neutral-3);
    border-radius: 3px;
}

.mb-15 {
    margin-bottom: 15px
}

:deep(.arco-form-item-extra) {
    width: 100%;
}

:deep(.arco-modal-footer) {
    margin-top: -20px;
}
</style>
